package com.hhxy.service;

import com.hhxy.mapper.UserMapper;
import com.hhxy.pojo.User;
import com.hhxy.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    SqlSessionFactory sqlSF = SqlSessionFactoryUtil.getSqlSF();
    /**
     * 登录功能
     */
    public User login(String username, String password){
        //1、调用工具类获取SqlSessionFactory对象
        //2、获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //3、获取Mapper接口对象
        UserMapper mapper = sqlS.getMapper(UserMapper.class);
        //4、执行SQL语句
        User user = mapper.select(username, password);
        //5、释放资源
        sqlS.close();
        return user;
    }
    /**
     * 注册功能
     */
    public boolean register(String username,String password){
        if(username == null || username == " "){
            return false;
        }
        //1、调用工具类对象获取SqlSessionFactory对象
        //2、获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //3、获取Mapper接口对象
        UserMapper mapper = sqlS.getMapper(UserMapper.class);
        //4、执行SQL语句
        User user = mapper.selectByUsername(username);
        if(user == null){
            //说明这个用户名没有重名。可以用来进行注册
            //5、开始注册
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(password);
            mapper.add(user1);
            sqlS.commit();//切记提交事物和关流
        }
        sqlS.close();
        //user==null true说明政策成功
        return user == null;//又是一个小细节，学废了吗
    }
}
